package qs.openxt.libs.util;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

public class AlbumUtil {
	public static String getFilePathFromContentUri(Uri uri, Activity context) {
		Cursor cursor = null;
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = context.getContentResolver().query(uri, proj, null, null,
					null);
			int column_index = cursor.getColumnIndexOrThrow(proj[0]);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return null;
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
	}
	
	public static String getFilePathFromID(String[] ids, Activity context) {
		Cursor cursor = null;
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, MediaStore.Images.Media._ID + "=? ", ids, null);
			int column_index = cursor.getColumnIndexOrThrow(proj[0]);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return null;
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
	}

	public static Uri getImageContentUri(Context context, java.io.File imageFile) {
		String filePath = imageFile.getAbsolutePath();
		Cursor cursor = null;
		try {
			cursor = context.getContentResolver().query(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
					new String[] { MediaStore.Images.Media._ID },
					MediaStore.Images.Media.DATA + "=? ",
					new String[] { filePath }, null);
			if (cursor != null && cursor.moveToFirst()) {
				int id = cursor.getInt(cursor
						.getColumnIndex(MediaStore.MediaColumns._ID));
				Uri baseUri = Uri
						.parse("content://media/external/images/media");
				return Uri.withAppendedPath(baseUri, "" + id);
			} else if (imageFile.exists()) {
				ContentValues values = new ContentValues();
				values.put(MediaStore.Images.Media.DATA, filePath);
				return context.getContentResolver().insert(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			} else {
				return null;
			}
		} catch (Exception e) {
			return null;
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
	}
}
